#include<stdio.h>
#include<malloc.h>

struct node{
	int num;
	struct node *next;
};

struct node *head;

int insert(int);//, struct node*);		//insert a number

int delnode(int);//, struct node*);		//delete a given number

int printlist();//struct node*);		//print the whole list

int main(){
	int choice, num;
	printf("----Linked List----\nWhat would you like to do?\n");
	printf("1. View List\n2. Insert Number\n3. Delete Number\n4. Exit\t");

	scanf("%d", &choice);
	head = NULL;
	do{
		if(head == NULL)
			printf("\nEmpty List right now");
		switch(choice){
			case 1: printlist();//head);
				break;
			case 2:	printf("\nEnter number to insert:");
				scanf("%d", &num);
				insert(num);//, head);
				break;
			case 3: printf("\nEnter number to delete:");
				scanf("%d", &num);
				delnode(num);//, head);
				break;
			case 4: printf("\nExiting Program");
				exit(0);
			default: printf("\nPushing back to menu");
		}
		printf("\nMenu: \n1. View List\n2. Insert number\n3. Delete number\n4. Exit");
		scanf("%d", &choice);
	}while(choice!=4);

	return 0;
}

int insert(int n){//, struct node* hd){
	if(head == NULL){	/* if this is the first element */
		struct node *p;
		p = (struct node*)malloc(sizeof(struct node));
		if(p == NULL){
			printf("\n--Memory Error--");
			return 0;
		}
		p->num = n;
		p->next = NULL;
		printf("\n--Node Created. Assigning--");
		head = p;
	}else{	/*if there are elements already, then traverse list*/
		struct node *p = head, *q;
		while(p){
			q = p;
			p = p->next;
		}
		p = (struct node*) malloc(sizeof(struct node));
		p->num = n;
		p->next = NULL;
		q->next = p;
	}
}

int delnode(int n){//, struct node** hd){
	if(head == NULL){
		printf("\nLinked List is empty");
		return 0;
	}else{
		struct node *p = head, *q, *prev = NULL;
		/* traverse list to the point where the node is to be deleted*/
		while(p->num != n && p){
			prev = p;
			p = p->next;
		}
		if(!p && p->num != n){	//if reached at end and number not found
			printf("\nNumber %d not found in the list", n);
		}else if(p == head){	//if the element to be deleted is the first one, then the head needs to be moved.
			printf("\nValue is at head");
			head = head->next;
			free(p);
		}else{			//if we are in the middle, then the head does not need to be moved, but the previous element needs to be linked to the next.
			printf("\nValue %d found and deleted", n);
			prev->next = p->next;
			free(p);
		}
	}
}

int printlist(){//struct node **hd){
	if(head == NULL){
		printf("\nLinked List is empty");
	}else{
		struct node *p = head, q;
		printf("\nPrinting list:");
		do{
			printf("\nValue: %d", p->num);
			p = p->next;
		}while(p);
		printf("\nDone.");
	}
}
